﻿using AutoMapper;
using IOA.MES.DataAccess.Entity;
using IOA.MES.DataAccess.Enum;
using IOA.MES.DataAccess.VModel;
using IOA.MES.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IOA.MES.Business
{
    /// <summary>
    /// 标片管理（错误代码：106001）
    /// </summary>
    public class StandardPieceMgr
    {
        private MESContext mesDb = new MESContext("MES");

        /// <summary>
        /// 获取标片对象
        /// </summary>
        /// <param name="pieceId">标片ID</param>
        /// <returns>标片对象</returns>
        public VStandardPiece GetStandardPiece(int pieceId)
        {
            var entity = pieceId <= 0 ? null : mesDb.StandardPieces.FirstOrDefault(_ => _.PkId == pieceId && _.Valid);
            return Mapper.Map<VStandardPiece>(entity);
        }

        /// <summary>
        /// 获取标片对象
        /// </summary>
        /// <param name="barCode">标片条码</param>
        /// <returns>标片对象</returns>
        public VStandardPiece GetStandardPiece(string barCode)
        {
            var entity = mesDb.StandardPieces.FirstOrDefault(_ => _.ProductCode == barCode && _.Valid);
            return Mapper.Map<VStandardPiece>(entity);
        }

        /// <summary>
        /// 编辑标片
        /// </summary>
        /// <param name="model">标片对象</param>
        public void EditStandardPiece(VStandardPiece model)
        {
            var component = mesDb.Components.AsNoTracking().FirstOrDefault(_ => _.BarCode == model.ProductCode && _.Valid);
            if (component != null)
            {
                throw new MultiLanBizException(106003);//该条码为生产组件条码，不可使用
            }
            if (model.PkId <= 0)
            {
                var exist = mesDb.StandardPieces.FirstOrDefault(_ => _.ProductCode == model.ProductCode && _.Valid);
                if (exist != null)
                {
                    throw new MultiLanBizException(106001);// "标片条码已存在");
                }

                model.Status = CommonStatus.Normal;
                model.CreateTime = DateTime.Now;
                mesDb.StandardPieces.Add(Mapper.Map<StandardPiece>(model));
                mesDb.SaveChanges();
            }
            else
            {
                var exist = mesDb.StandardPieces.FirstOrDefault(_ => _.PkId != model.PkId && _.ProductCode == model.ProductCode && _.Valid);
                if (exist != null)
                {
                    throw new MultiLanBizException(106001);// "标片条码已存在");
                }
                var entity = mesDb.StandardPieces.FirstOrDefault(_ => _.PkId == model.PkId && _.Valid);
                if (entity == null)
                {
                    throw new MultiLanBizException(106002);// "标片不存在，无法编辑");
                }

                mesDb.StandardPieces.Attach(entity);
                entity.ProductCode = model.ProductCode;
                entity.Model = model.Model;
                entity.Pmax = model.Pmax;
                entity.Voc = model.Voc;
                entity.Isc = model.Isc;
                entity.Vmp = model.Vmp;
                entity.Imp = model.Imp;
                entity.FF = model.FF;
                entity.PmaxToleranceDown = model.PmaxToleranceDown;
                entity.VocToleranceDown = model.VocToleranceDown;
                entity.IscToleranceDown = model.IscToleranceDown;
                entity.VmpToleranceDown = model.VmpToleranceDown;
                entity.ImpToleranceDown = model.ImpToleranceDown;
                entity.FFToleranceDown = model.FFToleranceDown;
                entity.PmaxToleranceUp = model.PmaxToleranceUp;
                entity.VocToleranceUp = model.VocToleranceUp;
                entity.IscToleranceUp = model.IscToleranceUp;
                entity.VmpToleranceUp = model.VmpToleranceUp;
                entity.ImpToleranceUp = model.ImpToleranceUp;
                entity.FFToleranceUp = model.FFToleranceUp;
                entity.StartDate = model.StartDate;
                entity.EndDate = model.EndDate;

                entity.ModifyBy = model.ModifyBy;
                entity.ModifyTime = DateTime.Now;

                mesDb.SaveChanges();
            }
        }

        /// <summary>
        /// 修改标片状态
        /// </summary>
        /// <param name="model">标片对象</param>
        public void ModifyStatus(VStandardPiece model)
        {
            var entity = mesDb.StandardPieces.FirstOrDefault(_ => _.PkId == model.PkId && _.Valid);
            if (entity == null)
            {
                throw new MultiLanBizException(106002);// "标片不存在，无法编辑");
            }

            entity.Status = model.Status;
            entity.ModifyBy = model.ModifyBy;
            entity.ModifyTime = DateTime.Now;

            mesDb.SaveChanges();
        }

        /// <summary>
        /// 查询标片列表
        /// </summary>
        /// <param name="page">页面索引</param>
        /// <param name="limit">页面容量</param>
        /// <param name="total">全部数量</param>
        /// <param name="code">标片条码</param>
        /// <param name="status">标片状态</param>
        /// <returns>标片列表</returns>
        public List<VStandardPiece> QueryPieces(int page, int limit, out int total, string code, CommonStatus? status)
        {
            var query = from piece in mesDb.StandardPieces.Where(_ => _.Valid)
                        select piece;
            if (!string.IsNullOrWhiteSpace(code))
            {
                query = query.Where(_ => _.ProductCode.Contains(code));
            }
            if (status.HasValue)
            {
                query = query.Where(_ => _.Status == status.Value);
            }

            total = query.Count();

            query = query.OrderByDescending(_ => _.PkId);
            var entities = limit <= 0 ? query.ToList() : query.Skip((page - 1) * limit).Take(limit).ToList();

            return Mapper.Map<List<VStandardPiece>>(entities);
        }
    }
}
